package org.wbd.pklib.web.listeners;

import java.util.Iterator;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
/**
 * klasa będąca słuchaczem cyklu jsf, wykorzystywana przy
 * podświetlaniu pól, ktęre nie przeszły walidacji
 * @author Marcin
 *
 */
public class SetFocusListener implements PhaseListener {
	public PhaseId getPhaseId() {

        // Listen on render response phase.
        return PhaseId.RENDER_RESPONSE;
    }

    /**
     * @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent)
     */
    public void beforePhase(PhaseEvent event) {

        // Init.
        FacesContext facesContext = event.getFacesContext();
        String focus = null;
        StringBuilder highlight = new StringBuilder();

        // Iterate over all client ID's with messages.
        Iterator<String> clientIdsWithMessages = facesContext.getClientIdsWithMessages();
        while (clientIdsWithMessages.hasNext()) {
            String clientIdWithMessages = clientIdsWithMessages.next();
            if (focus == null) {
                focus = clientIdWithMessages;
            }
            highlight.append(clientIdWithMessages);
            if (clientIdsWithMessages.hasNext()) {
                highlight.append(",");
            }
        }

        // Set ${focus} and ${highlight} in JSP.
        facesContext.getExternalContext().getRequestMap().put("focus", focus);
        facesContext.getExternalContext().getRequestMap().put("highlight", highlight.toString());
    }

    /**
     * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
     */
    public void afterPhase(PhaseEvent event) {
        // Do nothing.
    }
}
